package com.gitee.kamismile.stoneComEx.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

/**
 * OSS系统--- 模板配置
 * User: xujin
 * Date: 2010-1-18
 * Time: 13:07:14
 */
public class FreemarkerUtils {
    public static Template getTemplate(String path, String templateName) throws IOException {
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); //todo 过滤html let's go
        cfg.setDirectoryForTemplateLoading(new File(path));
        return cfg.getTemplate(templateName);
    }


    public static void writeHtml(String templatePath, String outPath, String temlateName, Map<String, Object> resultMap) throws IOException, TemplateException {
        Writer out = null;

        try {
            Template t = FreemarkerUtils.getTemplate(templatePath, temlateName + ".ftl");

            out = new OutputStreamWriter(new FileOutputStream(outPath), "utf-8");
            t.process(resultMap, out);
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static ByteArrayOutputStream writeWriter(String templatePath, String temlateName, Map<String, Object> resultMap) throws IOException, TemplateException {
        try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
             Writer out = new BufferedWriter(new OutputStreamWriter(arrayOutputStream));
        ) {
            Template t = FreemarkerUtils.getTemplate(templatePath, temlateName + ".ftl");
            t.process(resultMap, out);
            out.flush();
            return arrayOutputStream;
        }
    }

    public static void main(String[] args) throws IOException, TemplateException {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("time",new Date());
//        map.put("message","gpgpgp");
//        FreemarkerUtils.writeHtml("F:\\qqDownload","F:\\qqDownload\\a.html", "welcome", map);
//        ByteArrayOutputStream cc = writeWriter("F:\\qqDownload", "welcome", map);
//        ByteArrayInputStream aa = new ByteArrayInputStream(cc.toByteArray());
//        BufferedReader aab = new BufferedReader(new InputStreamReader(aa));
//        String line=null;
//        while((line=aab.readLine())!=null){
//            System.out.println(line);
//        }

        }
}
